//
//  Service+Storage.m
//  huimei
//
//  Created by fengyn on 16/1/20.
//  Copyright © 2016年 lexingsoft. All rights reserved.
//

#import "Service+Storage.h"
#import <Qiniu/QiniuSDK.h>
#import "UIImage+Watermark.h"
#import "Network.h"


@implementation ServiceManager(Storage)
+ (NSArray *)storageSpaceNames{
    return @[@"avatar",
             @"topic",
             @"diarybook",
             @"diary",
             @"question",
             @"categoryicon",
             @"common"];
}

+ (NSArray *)storageSpaceUrls{
    return @[@"http://o7rltue3j.bkt.clouddn.com/",
             @"http://7xq387.com2.z0.glb.qiniucdn.com/",
             @"http://7xpw6m.com2.z0.glb.qiniucdn.com/",
             @"http://7xpw67.com2.z0.glb.qiniucdn.com/",
             @"http://7xpw6n.com2.z0.glb.qiniucdn.com/",
             @"http://o7rljjhoy.bkt.clouddn.com/",
             @"http://o7oh8vwmd.bkt.clouddn.com/"];
}

+ (void)getTokenWithSpaceType:(StorageSpaceType)spaceType success:(void(^)(NSDictionary *data)) success failure:(void(^)(NSDictionary *data)) failure{
    NSString *spaceName=[self storageSpaceNames][spaceType];
    NSMutableDictionary *spaceTokenDic=[DataManager sharedInstance].spaceTokenDic;
    if (spaceTokenDic&&spaceTokenDic[spaceName]) {
        success(spaceTokenDic[spaceName]);
        return;
    }
    NSString *path = [NSString stringWithFormat:@"/storage/token/%@",spaceName];
    NSDictionary *parameterDict=nil;
    [NetworkClient getRequest:path parameters:parameterDict NeedPrompt:YES success:^(id dataObject) {
        if (![DataManager sharedInstance].spaceTokenDic) {
            [DataManager sharedInstance].spaceTokenDic=[NSMutableDictionary dictionary];
        }
        [[DataManager sharedInstance].spaceTokenDic setObject:dataObject forKey:spaceName];
        success(dataObject);
    } failure:^(id resultDict) {
        failure(resultDict);
    }];
}

+ (void)uploadImage:(UIImage *)image spaceType:(StorageSpaceType)spaceType success:(void(^)(NSDictionary *data)) success failure:(void(^)(NSDictionary *data)) failure {
    [self getTokenWithSpaceType:spaceType success:^(NSDictionary *data) {
        if ([data isKindOfClass:[NSString class]]) {
            UIImage *newImage=image;
            if (spaceType==StorageSpaceTypeAvatar) {
                
            }else{
                NSString *watermark=@"";
                if (![NSString checkNullString:[DataManager sharedInstance].watermarkOne]) {
                    watermark=[NSString stringWithFormat:@"%@",[DataManager sharedInstance].watermarkOne];
                }
                if (![NSString checkNullString:[DataManager sharedInstance].watermarkTwo]) {
                    watermark=[NSString stringWithFormat:@"%@\n%@",watermark,[DataManager sharedInstance].watermarkTwo];
                }else{
                    watermark=[NSString stringWithFormat:@"%@\n",watermark];
                }
                if (![NSString checkNullString:[DataManager sharedInstance].watermarkThree]) {
                    watermark=[NSString stringWithFormat:@"%@\n%@",watermark,[DataManager sharedInstance].watermarkThree];
                }
                if ([[DataManager sharedInstance].userType isEqualToString:@"DOCTOR"]) {
                    newImage=[image addWatermarkString:watermark];
                }else {
                    watermark=[NSString stringWithFormat:@"%@\n%@",@"会美APP",@"huimeiapp.com"];
                    newImage=[image addOneWatermarkString:watermark];
                }
            }
            NSString *fileName=[NSString stringWithFormat:@"%@.jpg",[NSUUID UUID].UUIDString];
            //上传带水印的图
            QNUploadManager *oldManager=[[QNUploadManager alloc] init];
            [oldManager putData:UIImageJPEGRepresentation(newImage, 1) key:[NSString stringWithFormat:@"wm-%@",fileName] token:(NSString *)data complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            } option:nil];
            
            //上传原图
            QNUploadOption *option=[[QNUploadOption alloc]initWithMime:nil progressHandler:^(NSString *key, float percent) {
                
            } params:nil checkCrc:NO cancellationSignal:^BOOL{
                return NO;
            }];
            QNUploadManager *uploadManager=[[QNUploadManager alloc] init];
            [uploadManager putData:UIImageJPEGRepresentation(image, 0.5) key:fileName token:(NSString *)data complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                success(resp);
            } option:option];
        }
    } failure:^(NSDictionary *data) {
        failure(data);
    }];
}

///本地下载文件目录
+ (NSString *)getDownloadDirectory
{
    NSFileManager *fm=[NSFileManager defaultManager];
    NSURL *documentPath=[[fm URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    NSURL *downloadPath=[documentPath URLByAppendingPathComponent:@"Download" isDirectory:YES];
    if (![fm fileExistsAtPath:downloadPath.absoluteString]) {
        if(![fm createDirectoryAtURL:downloadPath withIntermediateDirectories:YES attributes:nil error:nil])
        {
            NSLog(@"Couldn't create directory!");
        }
    }
    return downloadPath.absoluteString;
}

///根据文件名称返回本地磁盘文件路径
+ (NSString *)getLocationFilePathWithName:(NSString *)fileName
{
    NSString *downloadPath=[self getDownloadDirectory];
    NSString *filePath=[NSString stringWithFormat:@"%@%@",downloadPath,fileName];
    filePath=[filePath substringFromIndex:7];
    return filePath;
}

///根据远程Url返回本地磁盘文件路径
+ (NSString *)getLocationFilePathWithUrl:(NSString *)fileUrl
{
    NSURL *url=[NSURL URLWithString:fileUrl];
    NSString *name=url.lastPathComponent;
    return [self getLocationFilePathWithName:name];
}

///文件是否存在
+ (BOOL)fileExistsAtPath:(NSString *)filePath{
    return [[NSFileManager defaultManager] fileExistsAtPath:filePath];
}

+ (NSOperation *)downloadFileWithUrl:(NSString *)fileUrl
            downloadSuccess:(void (^)(NSString *localFilePath))success
            downloadFailure:(void (^)(NSError *error))failure
                   progress:(void (^)(float progress, NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))progress
{
    NSString *savePath=[self getLocationFilePathWithUrl:fileUrl];
    if ([[NSFileManager defaultManager] fileExistsAtPath:savePath]) {
        success(savePath);
        return nil;
    }
    NSOperation *operation=[NetworkClient downloadRequest:fileUrl parameters:nil savedPath:savePath downloadSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        success(savePath);
    } downloadFailure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failure(error);
    } progress:^(float progres, NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        progress(progres,bytesRead,totalBytesRead,totalBytesExpectedToRead);
    }];
    return operation;
}

///清理Download下的所有文件
+ (void)clearDownloadDirectory{
    [[NSFileManager defaultManager] removeItemAtURL:[NSURL URLWithString:[self getDownloadDirectory]] error:nil];
}

///删除file
+ (void)removeFileWithPath:(NSString *)filePath{
    NSError *error;
    if([[NSFileManager defaultManager] removeItemAtPath:filePath error:&error])
    {
        DLog(@"删除文件成功\n%@",filePath);
    }else{
        DLog(@"删除文件失败\n%@\nerror:%@",filePath,error);
    }
}
@end
